from main import models
from lib.checkout import CheckOut
from lib.logfactory import LogFactory
import sys

class Workflow:
    def __init__(self):
        lf = LogFactory()
        self.log = lf.get_default_logger('workflow')
        self.checkout = CheckOut()

    def mapreduce(self):
        #map tickets
        tickets = models.ticket.objects.filter(completed = False)
        for ticket in tickets:
            if ticket.mapped:
                if not models.unit.objects.filter(ticket=ticket).count():
                    ticket.completed=True
                    ticket.save()
                    continue
            self.log.debug('ticket '+str(ticket))
            #update ticket's mapreduce code
            self.log.debug('not mapped -> checkout ticket')
            completed = self.checkout.run('mapreduce/' + ticket.mapreduce.link + '/',self.log)
            if not completed:
                self.log.error('can\'t checkout mapreduce')
                return
            #import ticket's mapreduce module
            module_name = 'trunk.mapreduce.' + ticket.mapreduce.link
            print module_name
            try:
                __import__(module_name)
                processor = sys.modules[module_name]
            except:
                self.log.error('import failure')
            #proceed to mapreduce procedure
            if ticket.mapped:
                if not models.unit.objects.filter(ticket=ticket,status__gte=0).count():
                    print 'nothing to reduce for ticket',ticket.id
                    continue
                processor.reduce(models, ticket,self.log)
            else:
                processor.map(models, ticket,self.log)

    def count_tasks(self):
        tickets = models.ticket.objects.filter(completed=False).count()
        return tickets